package com.edu.koudingmusic.fragments;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.edu.koudingmusic.MainActivity;
import com.edu.koudingmusic.R;
import com.edu.koudingmusic.adapters.NetMusicAdapter;
import com.edu.koudingmusic.entities.SearchResult;
import com.edu.koudingmusic.tools.AppUtils;
import com.edu.koudingmusic.tools.Constant;
import com.edu.koudingmusic.tools.SearchMusicUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class NetMusicListFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {


    private static final String TAG = "NetMusicListFragment";
    private MainActivity mMainActivity;
    private LinearLayout mSearchBtnContainer;
    private LinearLayout mSearchContainer;
    private LinearLayout mLoadLayout;
    private ImageButton mSearchBtn;
    private EditText mSearchContent;
    private ListView mNetListMusic;


    private List<SearchResult> mSearchResults;


    // 搜索音乐的页码
    private int page = 1;
    private NetMusicAdapter mAdapter;

    public NetMusicListFragment() {
        // Required empty public constructor
    }

    public static NetMusicListFragment newInstance() {
        NetMusicListFragment fragment = new NetMusicListFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_net_music_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        initViews(view);
        super.onViewCreated(view, savedInstanceState);
    }

    // 初始化
    private void initViews(View view) {
        mSearchResults = new ArrayList<>();
        mSearchBtnContainer = (LinearLayout) view.findViewById(R.id.ll_search_btn_container);
        mSearchContainer = (LinearLayout) view.findViewById(R.id.ll_search_container);
        mLoadLayout = (LinearLayout) view.findViewById(R.id.load_layout);
        mSearchBtn = (ImageButton) view.findViewById(R.id.ib_search_btn);
        mSearchContent = (EditText) view.findViewById(R.id.et_search_content);
        mNetListMusic = (ListView) view.findViewById(R.id.listview_net_music);

        mNetListMusic.setOnItemClickListener(this);
        mSearchBtnContainer.setOnClickListener(this);
        mSearchBtn.setOnClickListener(this);
        loadNetData();
    }

    // 加载网络数据
    private void loadNetData() {
        // 显示
        mLoadLayout.setVisibility(View.VISIBLE);
        // 异步加载网络音乐
        Log.e(TAG, "loadNetData: " + Constant.BAIDU_URL + Constant.BAIDU_DAYHOT);
        new LoadNetDataTask().execute(Constant.BAIDU_URL + Constant.BAIDU_DAYHOT);
    }


    // 列表项的单击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position>=mAdapter.getSearchResults().size()|| position<0){
            return;
        }
        showDownloadDialog(position);

    }

    // 下载弹窗
    private void showDownloadDialog(final int position) {
        DownloadDialogFragment dialogFragment = DownloadDialogFragment.newInstance(mSearchResults.get(position));
        //dialogFragment.show(getFragmentManager(),"download");
        dialogFragment.show(getFragmentManager(),"download");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_search_btn_container:
                mSearchBtnContainer.setVisibility(View.GONE);
                mSearchContainer.setVisibility(View.VISIBLE);
                break;
            case R.id.ib_search_btn:
                //搜索时间处理
                searchMusic();
                break;
            default:
                break;
        }
    }

    // 搜索音乐
    private void searchMusic() {

        //隐藏输入法
        AppUtils.hideInputMethod(mSearchContent);
        mSearchBtnContainer.setVisibility(View.VISIBLE);
        mSearchContainer.setVisibility(View.GONE);
        String key = mSearchContent.getText().toString();
        if (TextUtils.isEmpty(key)){
            Toast.makeText(mMainActivity,"请输入关键词",Toast.LENGTH_SHORT).show();
            return;
        }
        mLoadLayout.setVisibility(View.VISIBLE);

        SearchMusicUtils.getInstance().setListener(new SearchMusicUtils.OnSearchResultListener() {
            @Override
            public void onSearchResult(ArrayList<SearchResult> searchResults) {
                List<SearchResult> results = mAdapter.getSearchResults();
                results.clear();
                results.addAll(searchResults);
                mAdapter.notifyDataSetChanged();
                mLoadLayout.setVisibility(View.GONE);
            }
        }).search(key,page);

    }

    class LoadNetDataTask extends AsyncTask<String, Void, Integer> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mLoadLayout.setVisibility(View.VISIBLE);
            mNetListMusic.setVisibility(View.GONE);
            mSearchResults.clear();
        }

        @Override
        protected Integer doInBackground(String... params) {
            String url = params[0];
            // 使用 jsoup 组件请求网络，并解析音乐数据
            try {
                Document doc = Jsoup.connect(url).userAgent(Constant.USER_AGENT).timeout(6 * 1000).get();
                Log.e(TAG, "doInBackground: doc 文本" + doc);
                Elements songTitles = doc.select("span.song-title");

                Elements artists = doc.select("span.author_list");
                for (int i = 0; i < songTitles.size(); i++) {
                    SearchResult searchResult = new SearchResult();
                    Elements urls = songTitles.get(i).getElementsByTag("a");
                    searchResult.setUrl(urls.get(0).attr("href"));
                    searchResult.setMusicName(urls.get(0).text());
                    //
                    Elements artistElements = artists.get(i).getElementsByTag("a");
                    searchResult.setArtist(artistElements.get(0).text());
                    searchResult.setAlbum("热歌榜");
                    mSearchResults.add(searchResult);
                }
                Log.e(TAG, "doInBackground: mSearchResults"+mSearchResults);
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
            return 1;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 1) {
                mAdapter = new NetMusicAdapter(mMainActivity, mSearchResults);
                mNetListMusic.setAdapter(mAdapter);
                mNetListMusic.addFooterView(LayoutInflater.from(mMainActivity).inflate(R.layout.footview_layout,null));
            }
            mLoadLayout.setVisibility(View.GONE);
            mNetListMusic.setVisibility(View.VISIBLE);
        }
    }
}
